package DAO

import (
	"CSMS/database"
	"database/sql"
	"fmt"
)

type Delivery struct {
	IndentNo       int            `db:"IndentNo"`
	GoodNo         int            `db:"GoodNo"`
	GoodNum        int            `db:"GoodNum"`
	DeliveryData   sql.NullString `db:"DeliveryData"`
	GoodTotalPrice int            `db:"GoodTotalPrice"`
}

type DeliveryInfo struct {
	Consignment Consignment
	Delivery    Delivery
	Good        Good
}

//InsertDelivery 插入一行数据
func (deliv *Delivery) InsertDelivery() {
	_, err := database.DB.Exec("insert INTO delivery(IndentNo,GoodNo,GoodNum,DeliveryData,GoodTotalPrice) values(?,?,?,?,?)", deliv.IndentNo, deliv.GoodNo, deliv.GoodNum, deliv.DeliveryData,deliv.GoodTotalPrice)
	if err != nil {
		fmt.Printf("Insert failed,err:%v", err)
		return
	}
}

//SelectDInfoByIndentNo 获取订单-商品信息
func SelectDInfoByIndentNo(indentNo int) []DeliveryInfo {
	var deliveryInfoList []DeliveryInfo
	rows, err := database.DB.Query(
		"SELECT good.GoodNo,good.GoodName,good.GoodPrice,delivery.GoodNum,delivery.DeliveryData "+
				"FROM delivery,good "+
				"WHERE delivery.IndentNo=? AND delivery.GoodNo=good.GoodNo", indentNo)
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err 43 :%v", err)
		return deliveryInfoList
	}
	var deliveryInfo DeliveryInfo
	for rows.Next() {
		err = rows.Scan(&deliveryInfo.Good.GoodNo, &deliveryInfo.Good.GoodName, &deliveryInfo.Good.GoodPrice, &deliveryInfo.Delivery.GoodNum, &deliveryInfo.Delivery.DeliveryData)
		if err != nil {
			fmt.Printf("Scan failed,err 50 :%v\n", err)
		}
		deliveryInfoList = append(deliveryInfoList, deliveryInfo)
	}
	return deliveryInfoList
}

//SelectTodayDelivery 选择固定日期的送货信息
func SelectTodayDelivery(nowDate string) []DeliveryInfo {
	var deliveryInfoList []DeliveryInfo
	rows, err := database.DB.Query(
		"SELECT GoodNo,GoodName,GoodNum,GoodTotalPrice,ConsignmentName,ConsignmentAdr,ConsignmentTel FROM todaydelivery WHERE DeliveryData=?", nowDate)
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err 43 :%v", err)
		return deliveryInfoList
	}
	var deliveryInfo DeliveryInfo
	for rows.Next() {
		err = rows.Scan(&deliveryInfo.Good.GoodNo, &deliveryInfo.Good.GoodName, &deliveryInfo.Delivery.GoodNum, &deliveryInfo.Delivery.GoodTotalPrice,&deliveryInfo.Consignment.ConsignmentName, &deliveryInfo.Consignment.ConsignmentAdr, &deliveryInfo.Consignment.ConsignmentTel)
		if err != nil {
			fmt.Printf("Scan failed,err 50 :%v\n", err)
		}
		deliveryInfoList = append(deliveryInfoList, deliveryInfo)
	}
	return deliveryInfoList
}
